package com.ruoyi.standingbook.v2toilet.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.convert.ExcelBigNumberConvert;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.erecord.region.service.IRegionService;
import com.ruoyi.standingbook.v2toilet.MapBean;
import com.ruoyi.standingbook.v2toilet.domain.bo.V2ToiletBo;
import com.ruoyi.standingbook.v2toilet.domain.vo.V2ToiletVo;
import com.ruoyi.standingbook.v2toilet.report.*;
import com.ruoyi.standingbook.v2toilet.service.IToiletService;
import com.ruoyi.stat.toilet.domain.vo.CommunityToiletStatVo;
import com.ruoyi.stat.toilet.logic.CommunityToiletStatLogic;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.*;

/**
 * V2市政公厕管养
 *
 * @author cc
 * @date 2023-06-07
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/toiletv2/toiletV2")
public class V2ToiletController extends BaseController {
    private final IRegionService regionService;
    private final IToiletService iToiletService;
    private final CommunityToiletStatLogic communityToiletStatLogic;
    //横向填充
    static FillConfig horizontal = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
    //纵向填充
    static FillConfig vertical = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build();

    @SaCheckPermission("toiletv2:toiletV2:export")
    @Log(title = "V2市政公厕管养日报", businessType = BusinessType.EXPORT)
    @PostMapping("/exportDaily")
    public void dailyExport(V2ToiletBo bo, HttpServletResponse response) throws IOException {

        ExcelUtil.resetResponse("市政公厕管养日报", response);
        ClassPathResource tplResource = new ClassPathResource("excel/v2toiletDay.xlsx");
        ExcelWriter writer = EasyExcel.write(response.getOutputStream())
            .registerWriteHandler(new CellStyleHander(7, 39, 12, 34))
            .withTemplate(tplResource.getStream()).build();

        String type = "1";
        //1.获取社区信息
        JSONObject regions = communityToiletStatLogic.getStreetsAndMonths(false, 1);
        List<Regions> regionsList = regions.getBeanList("regions", Regions.class);
        int i = 0;
        for (Regions street : regionsList) {
            WriteSheet sheet = EasyExcel.writerSheet(i).build();
            sheet.setSheetName(street.getLabel());
            JSONObject item = new JSONObject();
            item.set("street", street.getLabel());//街道名称
            //2.根据社区查询 获取街道或社区 公厕数量
            List<CommunityToiletStatVo> toiletCount = communityToiletStatLogic.getCommunityToiletStatNum(street.getId(), type);
            DayReportUtil.toiletCountData(toiletCount, writer, sheet, item);
            //JSONObject dayObject = communityToiletStatLogic.getCommunityToiletStatDate(street.getId(), "1", new Date());
            //            countDay(dayObject,writer, sheet, item, street.getId());
            JSONObject month = communityToiletStatLogic.getCommunityToiletStatMonth(street.getId(), type, new Date());
            DayReportUtil.countMonth(month, writer, sheet, item);
            JSONObject list = communityToiletStatLogic.getCommunityToiletStatDateAndMaxMin(street.getId(), type, new Date());
            DayReportUtil.listInfo(list, writer, sheet, item);
            writer.fill(item, sheet);
            i++;
            System.out.println(item);
        }
        writer.finish();
    }

    @SaCheckPermission("toiletv2:toiletV2:export")
    @Log(title = "V2市政公厕管养月报", businessType = BusinessType.EXPORT)
    @PostMapping("/exportMonth")
    public void monthlyExport(V2ToiletBo bo, HttpServletResponse response) throws IOException {


        JSONObject jsonObject = communityToiletStatLogic.getCommunityToiletStatMonthAndMaxMin(bo.getToiletName(), new Date());


        ExcelUtil.resetResponse("市政公厕管养月报", response);
        ClassPathResource templateResource = new ClassPathResource("excel/v2toiletMonth.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
            .withTemplate(templateResource.getStream())
            .autoCloseStream(false)
            // 大数值自动转换 防止失真
            .registerConverter(new ExcelBigNumberConvert())
            .registerWriteHandler(new CellStyleHander())
            .build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();

        //------------------------------------------------------
        //巡检项
        Map<String, Object> columns = JSONUtil.parseObj(jsonObject.get("columns"));

        //纵向填充
        excelWriter.fill(columns, writeSheet);//填充巡检项
        //------------------------------------------------------
        //        填充异常个数
        Map<String, Object> rcMap = MapUtils.newHashMap();
        //noinspection unchecked
        jsonObject.get("rc", Map.class).forEach((k, v) -> rcMap.put("rc".concat(k.toString()), v));
        //填充巡检项 END
        excelWriter.fill(rcMap, writeSheet);//填充异常个数
        //------------------------------------------------------

        List<V2ToiletReportBean> monthDay = new ArrayList<>();
        List<Map<String, String>> rowMap = new ArrayList<>();
        MonthReportUtil.itemDaySummary(jsonObject, rowMap, monthDay);
        //横向填充 日期
        excelWriter.fill(new FillWrapper("days", monthDay), horizontal, writeSheet);
        //横向填充
        excelWriter.fill(new FillWrapper("row", rowMap), horizontal, writeSheet);
        //------------------------------------------------------
        excelWriter.finish();
    }

    //@GetMapping("/monthly/{toiletName}/{queryDate}")
    //public R<JSONObject> monthlyPage(@PathVariable String toiletName, @PathVariable String queryDate) {
    @GetMapping("/monthly")
    public R<JSONObject> monthlyPage(V2ToiletBo bo) {

        if (StringUtils.isEmpty(bo.getToiletName()))
            return R.fail("公厕名称不允许为空，请核查参数");

        return R.ok(communityToiletStatLogic.getCommunityToiletStatMonthAndMaxMin(bo.getToiletName(), new Date()));
    }


    @Log(title = "社区和公厕查询条件可以组装成下拉列表", businessType = BusinessType.EXPORT)
    @GetMapping("/selectCondition")
    public Map<String, List<MapBean<String>>> selectCondition() {
        return iToiletService.selectCondition();
    }

    /**
     * 查询V2市政公厕管养列表
     */
    @SaCheckPermission("toiletv2:toiletV2:list")
    @GetMapping("/list")
    public TableDataInfo<V2ToiletVo> list(V2ToiletBo bo, PageQuery pageQuery) {
        return iToiletService.queryPageList(bo, pageQuery);
    }


    /**
     * 导出V2市政公厕管养列表
     */
    @SaCheckPermission("toiletv2:toiletV2:export")
    @Log(title = "V2市政公厕管养", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(V2ToiletBo bo, HttpServletResponse response) {
        List<V2ToiletVo> list = iToiletService.reportDetail(bo);
        ExcelUtil.exportExcel(list, "V2市政公厕管养", V2ToiletVo.class, response);
    }


    /**
     * 获取V2市政公厕管养详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("toiletv2:toiletV2:query")
    @GetMapping("/{id}")
    public R<V2ToiletVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable String id) {
        return R.ok(iToiletService.queryById(id));
    }

    /**
     * 新增V2市政公厕管养
     */
    @SaCheckPermission("toiletv2:toiletV2:add")
    @Log(title = "V2市政公厕管养", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody V2ToiletBo bo) {
        return toAjax(iToiletService.insertByBo(bo));
    }

    /**
     * 修改V2市政公厕管养
     */
    @SaCheckPermission("toiletv2:toiletV2:edit")
    @Log(title = "V2市政公厕管养", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody V2ToiletBo bo) {
        return toAjax(iToiletService.updateByBo(bo));
    }

    /**
     * 删除V2市政公厕管养
     *
     * @param ids 主键串
     */
    @SaCheckPermission("toiletv2:toiletV2:remove")
    @Log(title = "V2市政公厕管养", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iToiletService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
